import {
  type PropType,
  defineComponent,
  watch,
} from 'vue'

import {
  ElCard,
} from 'element-plus'

import { FormGrid, FormItem } from '@formily/element-plus'
import type { Form } from '@formily/core'
import Upload from '@/formily-components/Upload'
import { useTableSelect } from '@/hooks/usePageTable'

import type { Dict } from '@/utils/dict'
import { useDict } from '@/utils/dict'
import type { PageResponse } from '@/utils/request'
import SchemaForm from '@/components/SchemaForm'

export default defineComponent({
  props: {
    form: {
      type: Object as PropType<Form>,
    },
  },
  setup(props) {
    const dicts = useDict('deyu', 'zhiyu', 'laoyu', 'shenyu', 'nengyu')
    const dictMap = [
      ['德育', 'deyu', 'deTotal'],
      ['智育', 'zhiyu', 'zhiTotal'],
      ['劳育', 'laoyu', 'laoTotal'],
      ['身育', 'shenyu', 'shenTotal'],
      ['能育', 'nengyu', 'nengTotal'],
    ] as const

    const getData = (key: string) =>
      <T = Dict>() =>
        new Promise<PageResponse<T>>((resolve) => {
          if (Array.isArray(dicts[key].value) && dicts[key].value.length > 0) {
            resolve({ total: 1, rows: dicts[key].value as T[] })
          }
          else {
            watch(
              dicts[key],
              value => value && resolve({ total: 1, rows: value as T[] }),
              { once: true },
            )
          }
        })

    const schema = {
      type: 'object',
      properties: {
        layout: {
          'type': 'void',
          'x-component': 'FormGrid',
          'x-component-props': {
            maxColumns: [1, 2],
            columnGap: 40,
          },
          'properties': {
            year: {
              'type': 'string',
              'x-component': 'DatePicker',
              'x-decorator': 'FormItem',
              'title': '年份',
              'required': true,
            },
            partyMembers: {
              'type': 'string',
              'x-component': 'Radio.Group',
              'x-decorator': 'FormItem',
              'title': '是否党团员',
              'enum': [{ label: '是', value: '是' }, { label: '否', value: '否' }],
              'required': true,
            },
            studentLeader: {
              'type': 'string',
              'x-component': 'Radio.Group',
              'x-decorator': 'FormItem',
              'title': '是否学生干部',
              'enum': [{ label: '是', value: '是' }, { label: '否', value: '否' }],
              'required': true,
            },
            filePath: {
              'type': 'string',
              'title': '附件',
              'x-component': 'Upload',
              'x-decorator': 'FormItem',
              'x-component-props': {
                fileType: ['zip', 'tar', 'tar.gz', '7z'],
                fileSize: 40,
                limit: 10,
                tips: '提交申请材料（材料命名如：德育-德育义务献血）',
              },
            },
            ...dictMap.reduce(
              (pre, cur) => {
                const { TableSelect } = useTableSelect<Dict, number>(
                  {
                    getList: getData(cur[1]),
                  },
                  [
                    {
                      key: 'label',
                      title: '综测项目',
                    },
                    {
                      key: 'remark',
                      title: '得分',
                    },
                  ],
                  'multiple',
                  (row: Dict) => row.value,
                )
                return {
                  ...pre,
                  [cur[2]]: {
                    'type': 'string',
                    'x-component': TableSelect,
                    'x-decorator': 'FormItem',
                    'title': cur[0],
                  },
                }
              },
              {},
            ),
          },
        },
      },
    }

    return () => (
      <ElCard>
        <SchemaForm form={props.form} schema={schema} components={{ FormItem, FormGrid, Upload }} />
      </ElCard>
    )
  },
})
